package com.mymorningroutine;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mymorningroutine.server.ActivityTable;
import com.mymorningroutine.obj.Activity;
import android.view.View.*;
import com.mymorningroutine.server.*;
import com.mymorningroutine.obj.*;
import android.app.*;
import android.content.*;
import android.util.*;
import com.mymorningroutine.utils.*;
import android.widget.*;
import java.util.*;
import android.support.v4.widget.*;
import android.content.res.*;
import android.widget.AdapterView.*;

public class MainActivity extends FragmentActivity implements
ActionBar.TabListener
{
	public static final Integer CURRENT_ROUTINE_FRAGMENT_POSITION = 0;
	public static final Integer ACTIVITIES_FRAGMENT_POSITION = 1;
	public static final Integer SAVED_ROUTINES_FRAGMENT_POSITION = 2;
	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	public static	SectionsPagerAdapter mSectionsPagerAdapter;
    ActivityTable activityTable;
	RoutineTable routineTable;
	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	private DrawerLayout mDrawerLayout;

	private ListView mDrawerList;

	private String[] mDrawerValues;

	private TypedArray navMenuIcons;

	private ArrayList<DrawerItem> navDrawerItems;

	private DrawerItemAdapter adapter;

	private String TAG;
	
	
	
	@Override
	public void onTabReselected(ActionBar.Tab p1, FragmentTransaction p2)
	{
		// TODO: Implement this method
	}

	
	public static void reloadFragmentActivities()
	{
			CurrentRoutineSectionFragment routineFragment = (CurrentRoutineSectionFragment) mSectionsPagerAdapter.getItem(CURRENT_ROUTINE_FRAGMENT_POSITION);
		routineFragment.loadDailyActivities();
		
			ActivitySectionFragment activitiesFragment = (ActivitySectionFragment) mSectionsPagerAdapter.getItem(ACTIVITIES_FRAGMENT_POSITION);
		activitiesFragment.loadActivities();
		
		
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
		setTitleColor(getResources().getColor(R.drawable.home_actionbar_background));
		ActivityTable activityTable =	Singleton.getActivityTable(getApplicationContext());
		RoutineTable routineTable = Singleton.getRoutineTable(getApplicationContext());
		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		
	
		/*
		Build Drawer 
		*/
		
		mDrawerValues = getResources().getStringArray(R.array.drawer_values);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

		navMenuIcons = getResources()
                .obtainTypedArray(R.array.drawer_icons);
 
 
        navDrawerItems = new ArrayList<DrawerItem>();
 
        // adding nav drawer items to array
        navDrawerItems.add(new DrawerItem(mDrawerValues[0], navMenuIcons.getResourceId(0, -1)));
        navDrawerItems.add(new DrawerItem(mDrawerValues[1], null));
        navDrawerItems.add(new DrawerItem(mDrawerValues[2], null));
        navDrawerItems.add(new DrawerItem(mDrawerValues[3], navMenuIcons.getResourceId(3,-1)));
		//navDrawerItems.add(new DrawerItem(mDrawerValues[4], navMenuIcons.getResourceId(4,-1)));
		navDrawerItems.add(new DrawerItem(mDrawerValues[5], navMenuIcons.getResourceId(5,-1)));
 
        // Recycle the typed array
        navMenuIcons.recycle();
		 // setting the nav drawer list adapter
        adapter = new DrawerItemAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);
		
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		
		
		
 
       
 
        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(false);
        getActionBar().setHomeButtonEnabled(true);
		
		
		
		
		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
			getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
			.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
				@Override
				public void onPageSelected(int position)
				{
					//actionBar.setSelectedNavigationItem(position);
					setTitle(mSectionsPagerAdapter.getPageTitle(position));
					//mSectionsPagerAdapter.getItem(position).refreshFragment();
				}
			});
		
		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
		{
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
							 .setText(mSectionsPagerAdapter.getPageTitle(i))
							 .setTabListener(this));
		}
	}

	public ActivityTable getActivityTable()
	{
		if (activityTable == null)	
		{
			activityTable = Singleton.getActivityTable(getApplicationContext());
		}
		return activityTable;	
	}
	
	public RoutineTable getRoutineTable()
	{
		if (routineTable == null)	
		{
			routineTable = Singleton.getRoutineTable( getApplicationContext());
		}
		return routineTable;	
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Log.v(TAG,"onOptionsItemSelected :" + item.getTitle());
		// TODO: Implement this method
		Integer menuItemId = item.getItemId();
		switch(menuItemId) {
			case R.id.action_refresh_current_routine:
				mSectionsPagerAdapter.getItem( mViewPager.getCurrentItem()).refreshFragment();
				break;
			
			case R.id.action_switch_view:
			
				mSectionsPagerAdapter.getItem( mViewPager.getCurrentItem()).switchView();
				break;
	/*			
			case R.id.action_load_daily_activities:
				getRoutineFragment().loadDailyActivities();
				break;
			case R.id.action_load_saved_routine:
				
				Intent intentRoutine = new Intent(getApplicationContext(), DialogRoutines.class);
				startActivityForResult(intentRoutine, 3);
				
				
				break; */
			}
				return super.onOptionsItemSelected(item);
	}

	
	
	
	public static CurrentRoutineSectionFragment getRoutineFragment()
	{
		return 	(CurrentRoutineSectionFragment) mSectionsPagerAdapter.getItem(CURRENT_ROUTINE_FRAGMENT_POSITION);
	}


	@Override
	public void onTabSelected(ActionBar.Tab tab,
							  FragmentTransaction fragmentTransaction)
	{
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
		setTitle(mSectionsPagerAdapter.getPageTitle(tab.getPosition()));
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
								FragmentTransaction fragmentTransaction)
	{
	

	}

/*	@Override
	protected void onResumeFragments()
	{
		// TODO: Implement this method
		mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem()).refreshFragment();
		super.onResumeFragments();
	}*/

	

	

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter
	{
		private ArrayList<RefreshableFragment> fragmentList;
		public SectionsPagerAdapter(FragmentManager fm)
		{
			super(fm);
			fragmentList = new ArrayList<RefreshableFragment>();
			fragmentList.add(CURRENT_ROUTINE_FRAGMENT_POSITION, new CurrentRoutineSectionFragment());
			fragmentList.add(ACTIVITIES_FRAGMENT_POSITION, new ActivitySectionFragment());
			fragmentList.add(SAVED_ROUTINES_FRAGMENT_POSITION, new RoutineSectionFragment());
		}

		@Override
		public RefreshableFragment getItem(int position)
		{
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			RefreshableFragment fragment =	fragmentList.get(position);

			//Bundle args = new Bundle();
			//args.putInt(ActivitySectionFragment.ARG_SECTION_NUMBER, position + 1);
			//fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount()
		{
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position)
		{
			Locale l = Locale.getDefault();
			switch (position)
			{
				case 0:
					return getString(R.string.title_current_routine).toUpperCase(l);
				case 1:
					return getString(R.string.title_activities).toUpperCase(l);
				case 2:
					return getString(R.string.title_routines).toUpperCase(l);
			}
			return null;
		}
		
		


	}

	
	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	



	public class DrawerItemClickListener implements OnItemClickListener
	{

		@Override
		public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
		{
			// TODO: Implement this method
			if(p3 < 3)
				{	
				mViewPager.setCurrentItem(p3);
				mDrawerLayout.closeDrawers();
			}
			else if (p3 == 3)
				{
				Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
				startActivity(intent);
			}
		}
		
		
	}


	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	
	
	
	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	
	
	
	
	
}
